package com.sky.controller.admin;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sky.constant.MessageConstant;
import com.sky.constant.RedisKeyConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.result.Result;
import com.sky.service.DishFlavorService;
import com.sky.service.DishService;
import com.sky.service.SetmealDishService;
import com.sky.service.SetmealService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜品 前端控制器
 * </p>
 *
 * @author wang
 * @since 2023-07-06
 */
@RestController
@RequestMapping("/admin/dish")
@Transactional
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/page")
    public Result page(DishPageQueryDTO dishPageQueryDTO){
        Page<DishVO> dishPage = new Page<>(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        Page<DishVO> IdishPage = dishService.pageDish(dishPage,dishPageQueryDTO);
        return Result.success(dishPage);
    }

    /**
     * 菜品停售之后，相关套餐也会停售
     * @param statusId
     * @param id
     * @return
     */
    @PostMapping("/status/{statusId}")
    public Result updateStatus(@PathVariable Integer statusId,Long id){
        LambdaUpdateWrapper<Dish> dishLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        dishLambdaUpdateWrapper.eq(Dish::getId,id);
        dishLambdaUpdateWrapper.set(Dish::getStatus,statusId);
        boolean update = dishService.update(dishLambdaUpdateWrapper);
        if (statusId == 0){
            setmealService.upStatus(id);
        }
        Dish dish = dishService.getById(id);
        redisTemplate.delete(RedisKeyConstant.CACHE_DISH_BY_CATEGORYID+"::"+dish.getCategoryId());
        return Result.success(update ? "更新状态成功" : "操作失败，请刷新重试");
    }

    @DeleteMapping
    @CacheEvict(cacheNames = RedisKeyConstant.CACHE_DISH_BY_CATEGORYID,allEntries = true)   //清理所有缓存
    public Result delete(@RequestParam("ids") List<Long> ids){
        //判断菜品是否处于起售状态
        for (Long id : ids) {
            Dish dish = dishService.getById(id);
            if (dish.getStatus() == StatusConstant.ENABLE){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        //判断菜品是否被套餐关联了
        LambdaQueryWrapper<SetmealDish> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.in(SetmealDish::getDishId,ids);
        List<SetmealDish> setmealDishList = setmealDishService.list(setmealLambdaQueryWrapper);
        if (setmealDishList != null && setmealDishList.size() > 0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        dishFlavorService.removeByDishId(ids);
        dishService.removeByIds(ids);
//        Set keys = redisTemplate.keys(RedisKeyConstant.CACHE_DISH_BY_CATEGORYID);
//        redisTemplate.delete(keys);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result getDishById(@PathVariable Long id){
        Dish dish = dishService.getById(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        LambdaUpdateWrapper<DishFlavor> dishFlavorLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        dishFlavorLambdaUpdateWrapper.eq(DishFlavor::getDishId,id);
        List<DishFlavor> flavorList = dishFlavorService.list(dishFlavorLambdaUpdateWrapper);
        dishVO.setFlavors(flavorList);
        return Result.success(dishVO);
    }
    @PutMapping
    @CacheEvict(cacheNames = RedisKeyConstant.CACHE_DISH_BY_CATEGORYID,allEntries = true)   //清理所有缓存
    public Result updata(@RequestBody DishVO dishVO){
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishVO,dish);
        dishService.updateById(dish);
        List<DishFlavor> flavors = dishVO.getFlavors().stream().map((flavor) -> {
            flavor.setDishId(dish.getId());
            return flavor;
        }).collect(Collectors.toList());
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,dishVO.getId());
        dishFlavorService.remove(dishFlavorLambdaQueryWrapper);
        dishFlavorService.saveBatch(flavors);
//        Set keys = redisTemplate.keys(RedisKeyConstant.CACHE_DISH_BY_CATEGORYID);
//        redisTemplate.delete(keys);
        return Result.success();
    }


    @PostMapping
    @CacheEvict(cacheNames = RedisKeyConstant.CACHE_DISH_BY_CATEGORYID,key = "#dishVO.categoryId")
    public Result save(@RequestBody DishVO dishVO){
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishVO,dish);
        dishService.save(dish);
        if (dishVO.getFlavors() != null && dishVO.getFlavors().size() > 0){
            List<DishFlavor> flavors = dishVO.getFlavors().stream().map((flavor) -> {
                flavor.setDishId(dish.getId());
                return flavor;
            }).collect(Collectors.toList());
            dishFlavorService.saveBatch(flavors);
        }
        //清理缓存
        redisTemplate.delete(RedisKeyConstant.CACHE_DISH_BY_CATEGORYID+":"+dish.getCategoryId());
        return Result.success();
    }

    @GetMapping("/list")
    public Result listByCategoryId(Long categoryId,String name){
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(categoryId != null,Dish::getCategoryId,categoryId);
        dishLambdaQueryWrapper.like(StringUtils.isNotBlank(name),Dish::getName,name);
        dishLambdaQueryWrapper.eq(Dish::getStatus,StatusConstant.ENABLE);
        dishLambdaQueryWrapper.orderByDesc(Dish::getCreateTime);
        List<Dish> list = dishService.list(dishLambdaQueryWrapper);
        return Result.success(list);
    }

}
